package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 处理超时未支付订单
     */
    @Scheduled(cron = "0 0/1 * * * ?") // Every minute
    public void processTimeoutOrders() {
        log.info("Processing timeout orders...", new Date());

        // 当前时间减去15分钟
        LocalTime time = LocalTime.now().minusMinutes(15);

        List<Orders>  ordersList = orderMapper.getStatusAndOrderTime(Orders.PENDING_PAYMENT, time);
        for (Orders orders : ordersList) {
            orders.setStatus(Orders.CANCELLED);
            orders.setCancelReason("超时未支付，系统自动取消");
            orders.setCancelTime(LocalDateTime.from(LocalTime.now()));
            orderMapper.update(orders);
            log.info("Cancelled order: {}", orders.getId());
        }
    }

    @Scheduled(cron = "0 0 0 * * ?") // Every day at midnight
    public void processDeliveryOrders() {
        log.info("Processing delivery orders...", new Date());

        // 当前时间减去30分钟
        LocalTime time = LocalTime.now().minusMinutes(30);

        List<Orders>  ordersList = orderMapper.getStatusAndOrderTime(Orders.DELIVERY_IN_PROGRESS, time);

        if (ordersList.isEmpty()) {

            for (Orders orders : ordersList) {
                orders.setStatus(Orders.COMPLETED);
                orderMapper.update(orders);
            }
            log.info("Completed {} orders", ordersList.size());
        }

    }
}
